import { useDispatch } from "react-redux";
import "./login.less";
import Button from "@mui/material/Button";
import logo from "@/assets/images/logo.png";
import { TextField } from "@mui/material";
import { useState } from "react";
import { LoginApi, RegitserApi } from "@/api/index";
import { useNavigate } from "react-router-dom";
import useToast from "@/hooks/useToast/index";

export default function Login() {
  // 切换注册和登陆
  const [showReg, setshowReg] = useState(false);
  // 用户名
  const [username, setusename] = useState("12345678901");
  // 用户密码
  const [password, setpassword] = useState("wolfcode123");
  // 昵称
  const [nickName, setnickName] = useState("");
  // 跳转
  const navigate = useNavigate();
  // 自定义弹窗hook
  const Toast = useToast();

  // const dispatch = useDispatch<Dispatch<IToastAction>>();
  // 登陆注册
  const LoginReg = () => {
    if (showReg) {
      // 注册
      RegitserApi({
        phone: username,
        password: password,
      }).then((res) => {
        console.log(res);
      });
      console.log("register");
    } else {
      // 登陆
      LoginApi({
        username,
        password,
      }).then((res) => {
        // 1.提示框
        Toast("success", "登陆成功");
        // 2.存token
        localStorage.setItem("token", res.data);
        // 3.页面跳转
        navigate("/home");
      });
    }
  };

  return (
    <div className="login">
      <div className="logo">
        <img src={logo} alt="" />
      </div>
      <div>
        <p style={{ color: "#02369d", textAlign: "right", fontSize: "20px" }}>
          {!showReg ? " Login Page" : "Register Page"}
        </p>
      </div>
      <div className="row">
        <TextField
          fullWidth
          size="small"
          placeholder="请输入用户名"
          value={username}
          onChange={(e) => setusename(e.target.value)}
        />
      </div>
      <div className="row">
        <TextField
          type="password"
          fullWidth
          size="small"
          placeholder="请输入密码"
          value={password}
          onChange={(e) => setpassword(e.target.value)}
        />
      </div>
      <div className="btn">
        <Button variant="contained" fullWidth size="medium" onClick={LoginReg}>
          {!showReg ? "登陆" : "注册"}
        </Button>
      </div>
      <div className="row">
        <Button variant="text" onClick={() => setshowReg(!showReg)}>
          {!showReg ? "去注册" : "去登陆"}
        </Button>
      </div>
    </div>
  );
}
